﻿using DevExpress.ExpressApp;
using DevExpress.ExpressApp.Blazor.Components.Models;
using DevExpress.ExpressApp.Blazor.Layout;
using DevExpress.ExpressApp.Editors;
using DevExpress.ExpressApp.Model;
using System.Reflection;

namespace EasyXaf.MarkdownToolTip.Blazor;

public class MarkdownToolTipViewController : ViewController<DetailView>
{
    protected override void OnActivated()
    {
        base.OnActivated();

        if (View.LayoutManager is BlazorLayoutManager layoutManager)
        {
            layoutManager.ItemCreated += LayoutManager_ItemCreated;
        }
    }

    protected override void OnDeactivated()
    {
        if (View.LayoutManager is BlazorLayoutManager layoutManager)
        {
            layoutManager.ItemCreated -= LayoutManager_ItemCreated;
        }

        base.OnDeactivated();
    }

    private void LayoutManager_ItemCreated(object sender, BlazorLayoutManager.ItemCreatedEventArgs e)
    {
        if (e.ModelLayoutElement is IModelLayoutViewItem layoutViewItemModel)
        {
            var getCaptionMethod = typeof(BlazorLayoutManager).GetMethod("GetCaption", BindingFlags.NonPublic | BindingFlags.Instance);
            var caption = getCaptionMethod.Invoke(sender, [layoutViewItemModel, e.ViewItem]) as string;
            if (!string.IsNullOrWhiteSpace(caption) && e.ViewItem is PropertyEditor propertyEditor)
            {
                var markdownToolTipModel = (IModelMarkdownToolTip)propertyEditor.Model;
                var tooltip = propertyEditor.Model.ToolTip;
                tooltip = string.IsNullOrWhiteSpace(tooltip) ? markdownToolTipModel.MarkdownToolTip : tooltip;
                propertyEditor.Model.ToolTip = null;
                markdownToolTipModel.MarkdownToolTip = tooltip;
                if (!string.IsNullOrWhiteSpace(tooltip) && e.LayoutControlItem is DxFormLayoutItemModel itemModel)
                {
                    itemModel.CaptionTemplate = builder =>
                    {
                        builder.OpenComponent<MarkdownToolTipRenderer>(1);
                        builder.AddAttribute(2, "Caption", caption);
                        builder.AddAttribute(3, "ToolTip", tooltip);
                        builder.CloseComponent();
                    };
                }
            }
        }
    }
}
